<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      ref="crud"
      v-model="form"
      :permission="permissionList"
      :before-open="beforeOpen"
      :page.sync="page"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menu" slot-scope="{ row }">
        <el-button
          type="text"
          size="small"
          plain
          @click="getCreateQrCode(row.id)"
          >生成邀请二维码
        </el-button>
      </template>
      <template slot="menuLeft">
        <el-button
          type="info"
          size="small"
          plain
          v-if="permission.user_unlock"
          icon="el-icon-coordinate"
          @click="handleLock"
          >账号解封
        </el-button>
        <el-button
          type="info"
          size="small"
          plain
          v-if="permission.user_unlock"
          icon="el-icon-open"
          @click="handleEnable"
          >禁用/启用
        </el-button>
        <!-- <el-button type="success"
                    size="small"
                    plain
                    v-if="permission.user_import"
                    icon="el-icon-upload2"
                    @click="handleImport">导入
        </el-button>
        <el-button type="warning"
                    size="small"
                    plain
                    v-if="permission.user_export"
                    icon="el-icon-download"
                    @click="handleExport">导出
        </el-button> -->
      </template>
      <template slot-scope="{ row }" slot="tenantName">
        <el-tag>{{ row.tenantName }}</el-tag>
      </template>
      <!-- <template slot-scope="{row}"
                slot="roleName">
        <el-tag>{{row.roleName}}</el-tag>
        </template> -->

      <!-- <template slot-scope="{row}"
                slot="deptName">
        <el-tag>{{row.deptName}}</el-tag>
        </template> -->
      <template slot-scope="{ row }" slot="userTypeName">
        <el-tag>{{ row.userTypeName }}</el-tag>
      </template>
    </avue-crud>

    <el-dialog
      title="用户数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, enable, unlock, createQrCode } from '@/api/system/allUser'
import { getDeptLazyTree, getSelectList } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import { getToken } from '@/util/auth'

export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {},
      openType: '', //打开dialog弹框的类型
      search: {},
      excelBox: false,
      initFlag: true,
      selectionList: [],
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      init: {
        roleTree: [],
        deptTree: []
      },
      props: {
        label: 'title',
        value: 'key'
      },
      // treeDeptId: '',
      // treeData: [],
      // treeOption: {
      //   nodeKey: 'id',
      //   lazy: true,
      //   treeLoad: function (node, resolve) {
      //     const parentId = (node.level === 0) ? 0 : node.data.id;
      //     getDeptLazyTree(parentId).then(res => {
      //       resolve(res.data.data.map(item => {
      //         return {
      //           ...item,
      //           leaf: !item.hasChildren
      //         }
      //       }))
      //     });
      //   },
      //   addBtn: false,
      //   menu: false,
      //   size: 'small',
      //   props: {
      //     labelText: '标题',
      //     label: 'title',
      //     value: 'value',
      //     children: 'children'
      //   }
      // },
      option: {
        height: 'auto',
        calcHeight: 80,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: true,
        viewBtn: true,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        display: true,
        // dialogType: 'drawer',
        dialogClickModal: false,
        column: [
          {
            label: '用户平台',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=user_type',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number',
            search: true,
            hide: true,
            showColumn: false,
            display: false,
            prop: 'userType',
            rules: [
              {
                required: true,
                message: '请选择用户平台',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '用户平台',
            prop: 'userTypeName',
            slot: true,
            display: false
          },
          {
            label: '登录账号',
            prop: 'account',
            search: true,
            display: false
          },
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            display: false
          },
          // {
          //   label: "所属角色",
          //   prop: "roleName",
          //   slot: true,
          //   display: false
          // },
          // {
          //   label: "用户平台",
          //   prop: "userTypeName",
          //   slot: true,
          //   display: false
          // },
          {
            label: '所属租户',
            prop: 'tenantName',
            slot: true,
            display: false
          },
          {
            label: '所属公司',
            prop: 'compName',
            slot: true,
            display: false
          },
          {
            label: '所属部门',
            prop: 'deptName',
            slot: true,
            display: false
          },
          {
            label: '所属小组',
            prop: 'groupName',
            slot: true,
            display: false
          },
          {
            label: '用户类型',
            prop: 'userMoldName',
            slot: true,
            display: false
          },
          {
            label: '状态',
            prop: 'statusName',
            slot: true,
            display: false
          },
          {
            label: '状态',
            type: 'select',
            prop: 'status',
            display: false,
            hide: true,
            search: true,
            dicUrl: '/api/blade-system/dict/dictionary?code=login_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dataType: 'number'
          }
        ],
        group: [
          {
            label: '基础信息',
            prop: 'baseInfo',
            icon: 'el-icon-user-solid',
            column: [
              // {
              //   label: "所属租户",
              //   prop: "tenantId",
              //   type: "tree",
              //   dicUrl: "/api/blade-system/tenant/select",
              //   props: {
              //     label: "tenantName",
              //     value: "tenantId"
              //   },
              //   hide: !website.tenantMode,
              //   addDisplay: website.tenantMode,
              //   editDisplay: website.tenantMode,
              //   viewDisplay: website.tenantMode,
              //   rules: [{
              //     required: true,
              //     message: "请输入所属租户",
              //     trigger: "click"
              //   }],
              //   span: 24,
              // },
              {
                label: '登录账号',
                prop: 'account',
                rules: [
                  {
                    required: true,
                    message: '请输入登录账号',
                    trigger: 'blur'
                  }
                ]
              },
              // {
              //   label: "用户平台",
              //   type: "select",
              //   dicUrl: "/api/blade-system/dict/dictionary?code=user_type",
              //   props: {
              //     label: "dictValue",
              //     value: "dictKey"
              //   },
              //   dataType: "number",
              //   slot: true,
              //   prop: "userType",
              //   disabled: false,
              //   rules: [{
              //     required: true,
              //     message: "请选择用户平台",
              //     trigger: "blur"
              //   }]
              // },
              {
                label: '密码',
                prop: 'password',
                hide: true,
                editDisplay: false,
                viewDisplay: false,
                rules: [
                  { required: true, validator: validatePass, trigger: 'blur' }
                ]
              },
              {
                label: '确认密码',
                prop: 'password2',
                hide: true,
                editDisplay: false,
                viewDisplay: false,
                rules: [
                  { required: true, validator: validatePass2, trigger: 'blur' }
                ]
              }
            ]
          },
          {
            label: '详细信息',
            prop: 'detailInfo',
            icon: 'el-icon-s-order',
            column: [
              {
                label: '用户昵称',
                prop: 'name',
                hide: true,
                rules: [
                  {
                    required: true,
                    message: '请输入用户昵称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '用户姓名',
                prop: 'realName',
                rules: [
                  {
                    required: true,
                    message: '请输入用户姓名',
                    trigger: 'blur'
                  },
                  {
                    min: 2,
                    max: 5,
                    message: '姓名长度在2到5个字符'
                  }
                ]
              },
              {
                label: '手机号码',
                prop: 'phone',
                overHidden: true
              },
              {
                label: '电子邮箱',
                prop: 'email',
                hide: true,
                overHidden: true
              },
              {
                label: '用户性别',
                prop: 'sex',
                type: 'select',
                hide: true,
                dicData: [
                  {
                    label: '男',
                    value: 1
                  },
                  {
                    label: '女',
                    value: 2
                  },
                  {
                    label: '未知',
                    value: 3
                  }
                ],
                rules: [
                  {
                    required: true,
                    message: '请输入用户昵称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '用户生日',
                type: 'date',
                prop: 'birthday',
                format: 'yyyy-MM-dd hh:mm:ss',
                valueFormat: 'yyyy-MM-dd hh:mm:ss',
                hide: true
              },
              {
                label: '账号状态',
                prop: 'statusName',
                hide: true,
                display: false
              }
            ]
          },
          {
            label: '职责信息',
            prop: 'dutyInfo',
            icon: 'el-icon-s-custom',
            column: [
              {
                label: '用户类型',
                prop: 'userMold',
                type: 'select',
                dicUrl: '/api/blade-system/dict/dictionary?code=user_mold',
                slot: true,
                props: {
                  label: 'dictValue',
                  value: 'dictKey'
                },
                dataType: 'number',
                rules: [
                  {
                    required: true,
                    message: '请选择用户类型',
                    trigger: 'click'
                  }
                ]
              },
              {
                label: '所属公司',
                prop: 'companyId',
                type: 'select',
                dicData: [],
                slot: true,
                props: {
                  label: 'compName',
                  value: 'id'
                },
                change: ({ value }) => {
                  if (value) {
                    getSelectList('2', value).then((res) => {
                      const column = this.findObject(
                        this.option.group,
                        'deptId'
                      )
                      column.dicData = res.data.data
                    })
                  }
                },
                rules: [
                  {
                    required: true,
                    message: '请选择所属公司',
                    trigger: 'click'
                  }
                ]
              },
              {
                label: '所属部门',
                prop: 'deptId',
                type: 'select',
                dicData: [],
                slot: true,
                props: {
                  label: 'deptName',
                  value: 'id'
                },
                change: ({ value }) => {
                  if (value) {
                    getSelectList('3', value).then((res) => {
                      const column = this.findObject(
                        this.option.group,
                        'groupId'
                      )
                      column.dicData = res.data.data
                    })
                  }
                },
                rules: [
                  {
                    required: true,
                    message: '请选择所属部门',
                    trigger: 'click'
                  }
                ]
              },
              {
                label: '所属小组',
                prop: 'groupId',
                type: 'select',
                dicData: [],
                slot: true,
                props: {
                  label: 'groupName',
                  value: 'id'
                },
                rules: [
                  {
                    required: true,
                    message: '请选择所属小组',
                    trigger: 'click'
                  }
                ]
              }
            ]
          },
          {
            label: '权限信息',
            prop: 'menuInfo',
            icon: 'el-icon-s-custom',
            column: [
              // {
              //   label: "所属角色",
              //   prop: "roleId",
              //   multiple: true,
              //   type: "tree",
              //   dicData: [],
              //   props: {
              //     label: "title"
              //   },
              //   checkStrictly: true,
              //   slot: true,
              //   span: 24,
              //   rules: [{
              //     required: true,
              //     message: "请选择所属角色",
              //     trigger: "click"
              //   }]
              // },
              {
                prop: 'ids',
                labelWidth: 0,
                span: 24,
                formslot: true,
                slot: true,
                hide: true
              }
            ]
          }
        ]
      },
      data: [],
      platformQuery: {},
      platformSelectionList: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '模板上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '模板上传中，请稍等',
            span: 24,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: '/api/blade-user/import-user'
          },
          {
            label: '数据覆盖',
            prop: 'isCovered',
            type: 'switch',
            align: 'center',
            width: 80,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            value: 0,
            slot: true,
            rules: [
              {
                required: true,
                message: '请选择是否覆盖',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24
          }
        ]
      }
    }
  },
  watch: {
    // 'form.tenantId'() {
    //   if (this.form.tenantId !== '' && this.initFlag) {
    //     this.initData(this.form.tenantId);
    //   }
    // },
    'form.companyId'(newCompany, oldCompany) {
      if (newCompany !== oldCompany) {
        this.form.deptId = ''
        this.form.groupId = ''
      }
    },
    'form.deptId'(newDeptId, oldDeptId) {
      if (newDeptId !== oldDeptId) {
        // this.form.groupId = '';
        const column = this.findObject(this.option.group, 'groupId')
        column.dicData = []
      }
    },
    'excelForm.isCovered'() {
      if (this.excelForm.isCovered !== '') {
        const column = this.findObject(this.excelOption.column, 'excelFile')
        column.action = `/api/blade-user/import-user?isCovered=${this.excelForm.isCovered}`
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo', 'permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, false),
        viewBtn: this.vaildData(this.permission.user_view, false),
        delBtn: this.vaildData(this.permission.user_delete, false),
        editBtn: this.vaildData(this.permission.user_edit, false)
      }
    },
    ids() {
      let ids = []
      this.selectionList.forEach((ele) => {
        ids.push(ele.id)
      })
      return ids.join(',')
    }
  },
  mounted() {
    // 非租户模式默认加载管理组数据
    // if (!website.tenantMode) {
    // this.initData(website.tenantId);
    // }
  },
  methods: {
    getCreateQrCode(id) {
      this.loading = true
      createQrCode(id).then((res) => {
        // this.onLoad(this.page);
        this.loading = false;
        this.$message({
            type: 'success',
            message: res.data.data
          })
      },(error)=>{
        this.loading = false;
      })
    },
    searchReset() {
      this.query = {}
      // this.treeDeptId = '';
      this.onLoad(this.page)
    },
    searchChange(params, done) {
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
      done()
    },
    selectionChange(list) {
      this.selectionList = list
    },
    selectionClear() {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },
    handleLock() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择账号解封？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return unlock(this.ids)
        })
        .then(() => {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
    },
    handleEnable() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将用户状态更换？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return enable(this.ids)
        })
        .then(() => {
          this.onLoad(this.page, this.search)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        })
    },
    handleImport() {
      this.excelBox = true
    },
    uploadAfter(res, done, loading, column) {
      window.console.log(column)
      this.excelBox = false
      this.refreshChange()
      done()
    },
    handleExport() {
      this.$confirm('是否导出用户数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-user/export-user?${
            this.website.tokenHeader
          }=${getToken()}&account=${this.search.account}&realName=${
            this.search.realName
          }`
        )
      })
    },
    handleTemplate() {
      window.open(
        `/api/blade-user/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      )
    },
    /**
     * @func dialog打开回调
     * @desc 监听回调类型，调取接口，处理逻辑
     * @param {Function} done - 回调完成
     * @param {String} type - 打开类型
     * */
    beforeOpen(done, type) {
      this.openType = type
      getSelectList('1').then((res) => {
        const column = this.findObject(this.option.group, 'companyId')
        column.dicData = res.data.data
      })
      if (['edit', 'view'].includes(type)) {
      }
      this.initFlag = true
      done()
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    refreshChange() {
      this.onLoad(this.page, this.query)
    },
    onLoad(page, params = {}) {
      this.loading = true
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data
        this.page.total = data.total
        this.data = data.records
        this.loading = false
        this.selectionClear()
      })
    }
  }
}
</script>

<style>
.box {
  height: 800px;
}

.el-scrollbar {
  height: 100%;
}

.box .el-scrollbar__wrap {
  overflow: scroll;
}
</style>
